const app = getApp()
//banner
////////////定位
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk;
///////////
Page({
  data: {
    userInfo:false,
    /////////////////定位
    province: '',
    city: '',
    district: '',
    latitude: '',
    longitude: '',
    location:"",

    //////////////
    /////类型选择器
    selectShow: false,//控制下拉列表的显示隐藏，false隐藏、true显示
    selectData0: [{ category1Name: '请选择', category1Id:0}],//下拉列表的数据
    selectData: [],//下拉列表的数据
    index: 0,//选择的下拉列表下标
///////////////////////////////////////////////

    // 下拉菜单
    
    fours: '筛选',
    _num: 0,
    _res: 0,

    // 筛选
    
    chaoxiang: [{ name: '全部' }],
    
    
    four: 0,

    isShow: true,
    currentTab: 0,

    isMine:""
   
  },
  //////////////定位
  dingwei:function(){
    qqmapsdk = new QQMapWX({
      key: 'FSYBZ-5ZAW3-HSL3J-Y5VBG-PL6B7-6JBUN' //自己的key秘钥 http://lbs.qq.com/console/mykey.html 在这个网址申请
    });
    let that = this;
    that.getUserLocation();
  },

  getUserLocation: function () {
    let vm = this;
    wx.getSetting({
      success: (res) => {
        console.log(JSON.stringify(res))
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      vm.getLocation();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //调用wx.getLocation的API
          vm.getLocation();
        }
        else {
          //调用wx.getLocation的API
          vm.getLocation();
        }
      }
    })
  },
  // 微信获得经纬度
  getLocation: function () {
    let vm = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log(JSON.stringify(res))
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy;
        vm.getLocal(latitude, longitude)
      },
      fail: function (res) {
        console.log('fail' + JSON.stringify(res))
      }
    })
  },
  // 获取当前地理位置
  getLocal: function (latitude, longitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        console.log(JSON.stringify(res));
        let province = res.result.ad_info.province
        let city = res.result.ad_info.city
        let district = res.result.ad_info.district
        vm.setData({
          province: province,
          city: city,
          district: district,
          latitude: latitude,
          longitude: longitude,
          location: province + ' ' + city + ' ' + district
        })

        wx.setStorageSync("AddressArea", city);
        wx.setStorageSync("AddressDetail", district);
        wx.setStorageSync("Category1Id", "");
        /////////请求后台获取数据
        wx.request({
          url: app.globalData.baseUrl + '/order/findorderbyaddressarea',
          method: 'GET',
          data: { "addressArea": city, "addressDetail":"", "category10Id": "" },//传入的参数
          success: function (res) {
            var list = res.data.orders;
            console.log("list", list)
            if (list == null) {
              var toastText = '获取数据失败' + res.data.errMsg;
              wx.showToast({
                title: toastText,
                icon: '',
                duration: 2000
              });
            } else {
              vm.setData({
                orderList: list,





              });
            }
          }
        })

        //////////

      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        // console.log(res);
      }
    });
  },


  //////////////



   /////////////////回到顶部
  // 获取滚动条当前位置
  onPageScroll: function (e) {
    console.log(e)
    if (e.scrollTop > 100) {
      this.setData({
        floorstatus: true
      });
    } else {
      this.setData({
        floorstatus: false
      });
    }
  },

  //回到顶部
  goTop: function (e) {  // 一键回到顶部
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },



   ///////////////


  ///////类型选择器
  // 点击下拉显示框
  selectTap() {
    this.setData({
      selectShow: !this.data.selectShow
    });
  },
  // 点击下拉列表
  optionTap(e) {
    let Index = e.currentTarget.dataset.index;//获取点击的下拉列表的下标
    this.setData({
      index: Index,
      selectShow: !this.data.selectShow
    });
   console.log("category1Id", e.target.dataset.category1id)
    if (e.currentTarget.dataset.category1id != 0 && e.currentTarget.dataset.category1id != undefined) {
      var category1Id = e.currentTarget.dataset.category1id
      console.log("category1Id", e.currentTarget.dataset.category1id)
    } else {
      var category1Id = ''
      console.log("category1Id", e.currentTarget.dataset.category1id)
    }
    wx.setStorageSync("Category1Id", category1Id);
  },

  ////////
  

  // 下拉切换
  hideNav: function () {
    this.setData({
      displays: "none"
    })
  },
  // 区域
  tabNav: function (e) {
    this.setData({
      displays: "block"
    })
    this.setData({
      selected1: false,
      selected2: false,
      selected: true
    })
    if (this.data.currentTab === e.target.dataset.current) {
      return false;        
    } else {

      var showMode = e.target.dataset.current == 0;

      this.setData({
        //currentTab: e.target.dataset.current,
        isShow: showMode
      })
    }
  },
  // 下拉切换中的切换
  
  // 下拉菜单1 2 3 4
  
  
  

  // 筛选
  choseTxtColor: function (e) {
    var id = e.currentTarget.dataset.id; //获取自定义的ID值 
    console.log(e.currentTarget.dataset.id)
    this.setData({
      one: id
    })
  },
  chaoxiang: function (e) {
    var id = e.currentTarget.dataset.id; //获取自定义的ID值 
    this.setData({
      two: id
    })
  },
  


  //////地址选择器
  selectArea(e) {
    console.log(e.detail)
    this.setData({
      //address: e.detail,
      addressArea: e.detail[0].name + '-' + e.detail[1].name + '-' + e.detail[2].name
    })

  }, 
  qingchu:function(){
    this.setData({
      //address: e.detail,
      addressArea:"",
      addressDetail:"",
      index: 0,
      location:""
    })
    wx.setStorageSync("Category1Id", "");


  },
  queren:function(e){
    
    var that = this
    if (that.data.addressArea!=null){
      var addressArea = that.data.addressArea;
    }else{
      var addressArea=""
    }
    if (that.data.addressDetail != null) {
      var addressDetail = that.data.addressDetail;
    } else {
      var addressDetail = ""
    }
    
    wx.setStorageSync("AddressArea", addressArea);
    wx.setStorageSync("AddressDetail", addressDetail);
    
    
    wx.request({
      url: app.globalData.baseUrl +'/order/findorderbyaddressarea',
      method: 'GET',
      data: { "addressArea": addressArea, "addressDetail": addressDetail, "category10Id": wx.getStorageSync("Category1Id")},//传入的参数
      success: function (res) {
        var list = res.data.orders;
        console.log("list", list)
        if (list == null) {
          var toastText = '获取数据失败' + res.data.errMsg;
          wx.showToast({
            title: toastText,
            icon: '',
            duration: 2000
          });
        } else {
          that.setData({
            orderList: list,
            location: addressArea

            
            
            
          
            
          });
        }
      }
    })
    that.hideNav();

  },
  onShow:function(e){
    /////////////////////类型选择
    var that = this;
    wx.request({
      url: app.globalData.baseUrl + '/category1/listcategory1',
      method: 'GET',
      data: {},//传入的参数
      success: function (res) {
        var list = res.data.category1List;
        if (list == null) {
          var toastText = '获取数据失败' + res.data.errMsg;
          wx.showToast({
            title: toastText,
            icon: '',
            duration: 2000
          });
        } else {
          that.setData({
            selectData: that.data.selectData0.concat(list)
          });
          console.log("类型", that.data.selectData)
        }
      }
    })


    //////////////////////////jieshu
    //var that=this
    wx.request({
      url: app.globalData.baseUrl +'/order/findorderbyaddressarea',
      method: 'GET',
      data: { "addressArea": wx.getStorageSync("AddressArea"), "addressDetail": wx.getStorageSync("AddressDetail"), "category10Id": wx.getStorageSync("Category1Id")},//传入的参数
      success: function (res) {
        var list = res.data.orders;
        console.log("list", list)
        //////////////////////判断订单是否是自己的
        /*for (var i = 0; i < list.length;i++){
          console.log("buyerOpenid", list[i].buyerOpenid)
          var buyerOpenid = list[i].buyerOpenid
          console.log("Openid", wx.getStorageSync("openid"))
          if (buyerOpenid==wx.getStorageSync("openid") ){
            console.log("是否相等", buyerOpenid == wx.getStorageSync("openid"))
            that.setData({
              isMine: "我的订单"

            });
          }else{
            console.log("是否相等", buyerOpenid == wx.getStorageSync("openid"))
            that.setData({
              isMine: "查看详情"

            });
          }
        }*/


        ////////////////
        if (list == null) {
          var toastText = '获取数据失败' + res.data.errMsg;
          wx.showToast({
            title: toastText,
            icon: '',
            duration: 2000
          });
        } else {
          that.setData({
            orderList: list,
            myOpenId: wx.getStorageSync("openid")


          });
        }
      }
    })
  },
  //////授权
  login: function (e) {
    var that = this
    console.log(e);
    if (e.detail.errMsg.indexOf("ok") != -1) {
      //this.setData({ userInfo: e.detail.userInfo });
      //wx.setStorageSync("userInfo", e.detail.userInfo);//将对象存入本地缓存
      wx.setStorageSync("city", e.detail.userInfo.city);//将地址存入本地缓存
      console.log("这是.....：" + e.detail.userInfo.nickName);
      wx.login({
        success: function (res) {
          console.log("res...code..：" + res.code);
          //var code=res.code;
          wx.request({
            url: app.globalData.baseUrl + '/userinfo/login',
            method: "POST",
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            data: {//获取数据传到后台
              code: res.code,
              avatarUrl: e.detail.userInfo.avatarUrl,
              userName: e.detail.userInfo.nickName,
              userGender: e.detail.userInfo.gender,
              userCity: e.detail.userInfo.city,
              userProvince: e.detail.userInfo.province,
              userCountry: e.detail.userInfo.country,
            },

            success: function (res) {
              console.log("这是....：" + res.data.userInfo.buyerOpenid);
              const user = res.data.userInfo
              ///
              if (user == null) {
                var toastText = '获取数据失败' + res.data.errMsg;
                wx.showToast({
                  title: toastText,
                  icon: '',
                  duration: 2000
                });
              } else {
                // 将返回的数据保存到全局的缓冲中，方便其他页面使用
                wx.setStorageSync("openid", user.buyerOpenid);//将对象存入本地缓存
                wx.setStorageSync("userInfo", user);//将对象存入本地缓存
                that.setData({ userInfo: user });

              }

              // 将返回的数据保存到全局的缓冲中，方便其他页面使用
              // wx.setStorageSync("openid", openid);//将对象存入本地缓存
            }
          })
        }
      })

    }
  },
  getDetail: function (e) {
    var url1 = '../../order/orderdetail/orderdetail?orderId=' + e.currentTarget.dataset.orderid
    console.log("url1:" + url1)
    wx.navigateTo({
      url: url1
    })

  },
  jiedan:function(e){
    var url1 = '../order/jiedan/jiedan?orderId=' + e.currentTarget.dataset.orderid
    console.log("url1:" + url1)
    wx.navigateTo({
      url: url1
    })
    
  },
///////////////////////////

  onLoad: function (options) {
    
    var that = this
    let userInfo = wx.getStorageSync("userInfo");
    //console.log("userInfo：", userInfo)
    //if (null != userInfo && "" != userInfo&& userInfo!=undefined) {
    /*if (app.globalData.isok == true) {
      that.setData({ userInfo: userInfo });
      //that.getUnRead();
    }*/
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          //app.globalData.isok = true;
          that.setData({ userInfo: userInfo });
          
        }
      }
    })
     

   
    


  },

  /*******下拉刷新********* */
  // 页面下拉刷新

  // 下拉刷新
  onPullDownRefresh: function () {
    // 显示顶部刷新图标
    wx.showNavigationBarLoading();
    var that = this;
    that.setData({
      orderList: null
    });
    setTimeout(function () {
      that.onShow()
      // 隐藏导航栏加载框
      wx.hideNavigationBarLoading();
      // 停止下拉动作
      wx.stopPullDownRefresh();
    }, 1500);
    
  },


  

})


